package com.lc.filter;

import com.lc.bean.Users;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:防止用户未经登录直接进入页面
 * @author: ManolinCoder
 * @time: 2021/8/23
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //防止用户在未登录的情况下访问相应页面
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String URI = request.getRequestURI();//获得请求地址
        Users currentUser = (Users) request.getSession().getAttribute("currentUser");
        //如果当前访问了非login.jsp页面(除了初始页面、login.jsp页面、登录相关servlet请求地址以外)
        //并且currentUser为null，那说明你没登录就访问了。
        if (!URI.equals("/") && !URI.endsWith("login.jsp") && !URI.endsWith("login") && currentUser==null){
            //未登录直接重定向到登录页
            response.sendRedirect("login.jsp");
            return ;
        }

        //调取下一个过滤器或servlet
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
